package com.widget.picker;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.widget.picker.ZX_PopupWindow;
import com.widget.picker.kankan.wheel.widget.OnWheelChangedListener;
import com.widget.picker.kankan.wheel.widget.OnWheelScrollListener;
import com.widget.picker.kankan.wheel.widget.WheelView;
import com.widget.picker.kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import com.widget.picker.kankan.wheel.widget.adapters.NumericWheelAdapter;

import java.util.ArrayList;

public class CustomListPickers extends ZX_PopupWindow {

    private View mMenuView;

    private Context context;

    // 标题
    private TextView picker_title;

    // 完成，取消按键
    private Button btn_submit, btn_cancel;

    // 选择器布局
    private LinearLayout picker_list_layout;

    // 选择器listView
    private WheelView[] wheelView;
    private ArrayWheelAdapter[] adapters;

    // 数据源
    private ArrayList<ArrayList<String>> list;

    // 结果集
    private String[][] result;

    // 适配器ID
    private int adapterID;

    //常量
    private final int MAX_TEXT_SIZE = 20;
    private final int MIN_TEXT_SIZE = 17;

    public CustomListPickers(Context context, PickerSelListener l) {
        super(context);

        this.context = context;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.getRCode("layout", "picker_custom"), null);

        // 获取布局
        picker_title = (TextView) mMenuView.findViewById(R.getRCode("id", "picker_title"));

        // 获取按钮
        btn_submit = (Button) mMenuView.findViewById(R.getRCode("id", "picker_complete"));
        btn_cancel = (Button) mMenuView.findViewById(R.getRCode("id", "picker_cancel"));

        // 获取布局
        picker_list_layout = (LinearLayout) mMenuView.findViewById(R.getRCode("id", "picker_list_layout"));

        setPickerSelListener(l);

        // 设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.getRCode("style", "AnimBottom"));
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.getRCode("id", "picker_layout")).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
    }

    /**
     * @param title        标题
     * @param list         数据源
     * @param adapterID    适配器ID
     * @param visibleItems 显示条数
     * @param isCyclic     是否循环
     * @param currentItem  选中标记
     */
    public void init(String title, ArrayList<ArrayList<String>> list, int adapterID, int visibleItems, boolean isCyclic, String currentItem) {

        picker_title.setText(title);
        this.list = list;
        this.adapterID = adapterID;

        // 清空布局中所有view
        picker_list_layout.removeAllViews();

        // 初始化选择器
        wheelView = new WheelView[list.size()];
        adapters = new ArrayWheelAdapter[list.size()];

        // 初始化结果集
        result = new String[2][list.size()];

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        layoutParams.weight = 1;
        for (int i = 0; i < list.size(); i++) {
            wheelView[i] = new WheelView(context);
            wheelView[i].setId(i);
            wheelView[i].setLayoutParams(layoutParams);

            switch (adapterID) {
                case 0:

                    adapters[i] = new ArrayWheelAdapter(context, list.get(i), list.get(i).indexOf(currentItem), MAX_TEXT_SIZE, MIN_TEXT_SIZE);
                    wheelView[i].setViewAdapter(adapters[i]);
                    break;
                case 1:
                    wheelView[i].setViewAdapter(new NumericWheelAdapter(context, Integer.parseInt(list.get(i).get(0)), Integer.parseInt(list.get(i).get(1))));
                    break;
                default:
                    break;
            }

            // 设置显示条数
            wheelView[i].setVisibleItems(visibleItems);
            // 是否循环滚动
            wheelView[i].setCyclic(isCyclic);

            wheelView[i].setCurrentItem(adapters[i].currentIndex);

            result[0][i] = String.valueOf(wheelView[i].getCurrentItem());
            result[1][i] = (String) adapters[i].getItemText(wheelView[i].getCurrentItem());

            picker_list_layout.addView(wheelView[i]);
        }

        btn_submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (pickerSelListener != null) {
                    pickerSelListener.complete(result[0], result[1]);
                }
                dismiss();
            }
        });

        btn_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dismiss();
            }
        });

        initListener();
    }

    /**
     * 初始化滚动监听事件
     */
    private void initListener() {


        for (int i = 0; i < wheelView.length; i++) {

            final int b = i;

            wheelView[i].addChangingListener(new OnWheelChangedListener() {
                @Override
                public void onChanged(WheelView wheel, int oldValue, int newValue) {
                    String currentText = (String) adapters[b].getItemText(wheel.getCurrentItem());
                    setTextViewStyle(currentText, adapters[b]);
                    result[0][b] = String.valueOf(wheel.getCurrentItem());
                    result[1][b] = currentText;
                }
            });

            wheelView[i].addScrollingListener(new OnWheelScrollListener() {

                @Override
                public void onScrollingStarted(WheelView wheel) {

                }

                @Override
                public void onScrollingFinished(WheelView wheel) {
                    String currentText = (String) adapters[b].getItemText(wheel.getCurrentItem());
                    setTextViewStyle(currentText, adapters[b]);
                    result[0][b] = String.valueOf(wheel.getCurrentItem());
                    result[1][b] = currentText;
                }
            });
        }
    }

    /**
     * 设置文字的大小
     *
     * @param curriteItemText
     * @param adapter
     */
    public void setTextViewStyle(String curriteItemText, ArrayWheelAdapter adapter) {
        ArrayList<View> arrayList = adapter.getTestViews();
        int size = arrayList.size();
        String currentText;
        for (int i = 0; i < size; i++) {
            TextView textvew = (TextView) arrayList.get(i);
            currentText = textvew.getText().toString();
            if (curriteItemText.equals(currentText)) {
                textvew.setTextSize(MAX_TEXT_SIZE);
                textvew.setTextColor(context.getResources().getColor(R.getRCode("color", "text_10")));
            } else {
                textvew.setTextSize(MIN_TEXT_SIZE);
                textvew.setTextColor(context.getResources().getColor(R.getRCode("color", "text_11")));
            }
        }
    }

    public class ArrayWheelAdapter extends AbstractWheelTextAdapter {

        ArrayList<String> list;

        protected ArrayWheelAdapter(Context context, ArrayList<String> list, int currentItem, int maxsize, int minsize) {
            super(context, R.getRCode("layout", "picker_item"), R.getRCode("id", "tempValue"), currentItem, maxsize, minsize);
            for (String str : list) {
                Log.e("str", str);
            }
            this.list = list;
        }


        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            String str = list.get(index) + "";
            return str;
        }
    }

    public interface PickerSelListener {
        void complete(String[] index, String[] result);
    }

    public PickerSelListener pickerSelListener;

    public void setPickerSelListener(PickerSelListener l) {
        pickerSelListener = l;
    }
}
